{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "73bd968b-d970-4a05-94ef-4e7abf990827",
   "metadata": {},
   "source": [
    "Chapter 04\n",
    "\n",
    "# 代数式转化为函数\n",
    "Book_3《数学要素》 | 鸢尾花书：从加减乘除到机器学习 (第二版)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88c0c570-5dec-4096-a389-ad75aba13b22",
   "metadata": {},
   "source": [
    "该代码使用`sympy`库创建了一个代数表达式并将其转换为可计算的Python函数。首先，定义表达式：\n",
    "\n",
    "$$\n",
    "\\text{expr} = x^3 + 2x^2 - x - 2\n",
    "$$\n",
    "\n",
    "然后，使用`lambdify`将表达式$\\text{expr}$转换为一个可以接受数值输入的Python函数$f_x$。通过这种转换，可以直接对函数$f_x$进行数值计算。代码计算了当$x=1$时的函数值：\n",
    "\n",
    "$$\n",
    "f_x(1) = 1^3 + 2 \\cdot 1^2 - 1 - 2 = 0\n",
    "$$\n",
    "\n",
    "这一过程将符号表达式转化为数值计算函数，使表达式能够用于具体值的求解或进一步的数值分析。这种符号到函数的转换对于需要多次计算表达式值的情况非常方便，例如在数值模拟和数据分析中。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e816e3f3-a979-461a-bf66-f54d00a807ad",
   "metadata": {},
   "source": [
    "## 定义表达式并创建对应的函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cbbb261f-e58b-41e0-9761-9e4c1d947190",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle x^{3} + 2 x^{2} - x - 2$"
      ],
      "text/plain": [
       "x**3 + 2*x**2 - x - 2"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sympy.abc import x, y, z\n",
    "\n",
    "expr = x**3 + 2*x**2 - x - 2  # 定义表达式expr\n",
    "expr  # 输出表达式expr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "5e0ce9cd-81d6-4ab2-8f14-faaae20728f2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n"
     ]
    }
   ],
   "source": [
    "from sympy.utilities.lambdify import lambdify\n",
    "\n",
    "f_x = lambdify(x, expr)  # 将表达式转换为可计算的Python函数f_x\n",
    "\n",
    "print(f_x(1))  # 计算f_x在x=1时的值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85a80909-2aac-49ed-bb7a-f8cc6b80ee7d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ecd322f4-f919-4be2-adc3-69d28ef25e69",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
